<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="6" >
            <a-form-model-item label="单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-input v-model="model.code" placeholder="请输入单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="业务节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="code">
              <a-space>
                <j-dict-select-tag style="width: 200px" disabled type="list" v-model="model.businessNode"
                                   dictCode="business_node_type" placeholder="请选择业务节点" />
                <a-button :disabled="typeof model.noticeId != 'undefined'" style="margin-left: -10px" @click="onSearchBussiness">请选择业务节点</a-button>
              </a-space>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialTypeName">
              <a-input v-model="model.materialTypeName" disabled placeholder="物料大类" ></a-input>
              <a-input v-model="model.materialTypeCode" v-show="false" placeholder="物料大类" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="业务类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="businessType">
              <j-dict-select-tag disabled type="list" v-model="model.businessType"
                                 dictCode="business_type" placeholder="请选择业务类型"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseId">
              <a-input v-model="model.warehouseId" placeholder="请输入仓库" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="上级单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="superiorCode">
              <a-input v-model="model.superiorCode" placeholder="请输入上级单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="入库日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storageDate">
              <j-date placeholder="请选择入库日期" v-model="model.storageDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="经办人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlingPersonnelId">
              <a-input v-model="model.handlingPersonnelId" placeholder="请输入经办人员" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="经办人员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="handlingPersonnel">
              <a-input v-model="model.handlingPersonnel" placeholder="请输入经办人员" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="批次号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="lotNumber">
              <a-input v-model="model.lotNumber" placeholder="请输入批次号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="生产车间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="workshop">
              <a-input v-model="model.workshop" placeholder="请输入生产车间" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <a-input-number v-model="model.status" placeholder="请输入状态" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="成品入库单明细" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="bussProductStorageDetailTable.loading"
          :columns="bussProductStorageDetailTable.columns"
          :dataSource="bussProductStorageDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :toolbarConfig="{slot: ['prefix', 'suffix'], btn: [ 'remove', 'clearSelection']}"
          :edit-config="editConfig"
          @edit-disabled="editDisabledEvent"
          :row-class-name="rowClassName"
        >
          <template    v-slot:toolbarSuffix>
            <a-button @click='addMaterial' v-if='true'>新增</a-button>
            <a-button @click='copyDataModal' v-if='true'>复制</a-button>
            <a-button @click='pasteData' v-if='true'>黏贴</a-button>
            <!--            <a-button @click='' v-show="model.storageType == 0">新增</a-button>-->
            <!--  <a-button @click='addMaterial' >新增</a-button>-->
            <!--            <a-button @click='editMaterial' v-show=" bussStorageDetailTable.dataSource.length > 0 " >编辑</a-button>-->
            <!--          <a-button @click='addMaterial' v-if='!procurementShow && model.type'>新增物料</a-button>-->
          </template>
          <template v-slot:erpLocationName="props">
            <tsl-warehouse v-model="props.value" :disabled="(props.row.isDelete && props.row.isDelete === 1) || formDisabled" :rowData='props' @handlerOk="warehouseOk"></tsl-warehouse>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <bussiness-type-list ref="bussinessType" @handleOk="bussinessOk" :businessNode="3" ></bussiness-type-list>
    <erp-good-list ref='good'
                   @handlerOk='goodOk'
                   checkval='checkbox' :category="1"></erp-good-list>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import BussinessTypeList from '@/views/modules/business/BusinessTypeList'
  import ErpGoodList from '@/views/modules/goods/ErpGoodsListModal'
  import moment from 'dayjs'
  import TslWarehouse from '@comp/tsl/TslWarehouse.vue'
  import { Modal } from 'ant-design-vue';

  export default {
    name: 'BussProductStorageForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,BussinessTypeList,ErpGoodList,TslWarehouse
    },
    data() {
      return {
        moment,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
        },
        tableRef: '',
        refKeys: ['bussProductStorageDetail', ],
        tableKeys:['bussProductStorageDetail', ],
        activeKey: 'bussProductStorageDetail',
        // 成品入库单明细
        bussProductStorageDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料编号',
              key: 'materialCode',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '客户物料编号',
              key: 'customerMaterialCode',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '物料id',
              key: 'materialId',
               type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '数量',
              key: 'num',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助单位',
              key: 'supportUnit',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '辅助数量',
              key: 'supportNum',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '库位',
              key: 'erpLocationId',
              type: JVXETypes.slot,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              slotName: "erpLocationName"
            },
            {
              title: '物料批号',
              key: 'materialLotnumber',
               type: JVXETypes.input,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '限用日期',
              key: 'expiredDate',
              type: JVXETypes.date,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '生产日期',
              key: 'createDate',
              type: JVXETypes.date,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '质检状态',
              key: 'status',
              type: JVXETypes.normal,
              width:"150px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '备注',
              key: 'remark',
              type: JVXETypes.input,
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '成品入库单id',
              key: 'productStorageId',
               type: JVXETypes.hidden,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
          ]
        },
        url: {
          add: "/business/bussProductStorage/add",
          edit: "/business/bussProductStorage/edit",
          queryById: "/business/bussProductStorage/queryById",
          bussProductStorageDetail: {
            list: '/business/bussProductStorage/queryBussProductStorageDetailByMainId'
          },
        },
        num: 1,
        copydata: {},
        editConfig: {trigger: 'click', mode: 'cell', showStatus: true,activeMethod: this.activeRowMethod },
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
    },
    mounted() {
      this.getAllTable().then(tables=>{
        this.tableRef = tables[0]
      })
      setTimeout(() => {
        if(!this.model.id){
          let rows = this.tableRef.getNewDataWithId()
          this.tableRef.removeRowsById(rows[0].id)
        }
      },100)
    },
    methods: {
      rowClassName({ row, rowIndex }) {
        // 根据行数据动态返回 CSS 类名
        if (row.isDelete && row.isDelete === 1) {
          return 'frozen-row';
        }
        // 默认情况下不设置特定背景色
        return '';
      },
      editDisabledEvent ({ row, column }) {
        alert('禁止编辑')
      },
      activeRowMethod({ row, column }) {
        if(row.isDelete && row.isDelete == 1){
          return false
        }
        // 自定义禁用编辑的逻辑，返回 true 表示禁用编辑
        return true; // 示例：禁用 disabled 字段为 true 的行，以及 gender 列
      },
      copyDataModal(){
        // 复制数据
        let rows =  this.tableRef.selectedRows;
        if(rows.length === 0 || rows.length > 1){
          this.$message.warn('请选择一条入库信息！')
          return;
        }
        let _this = this
        Modal.confirm({
          title: () => '复制数据',
          content: () => (
            <div>
              <a-space>
                <span>复制行数</span>
                <a-input-number  v-model={this.num} min={1} max={10} step={1} precision={1} formatter={this.formatInteger} parser={this.parseInteger}/>
              </a-space>
            </div>
          ),
          onOk() {
            _this.copyData()
          },
          onCancel() {},
        });
      },
      formatInteger(value) {
        if (value === '') return '';
        const intValue = parseInt(value, 10);
        return isNaN(intValue) ? '' : String(intValue);
      },
      parseInteger(value) {
        return parseInt(value, 10);
      },
      copyData(){
        this.copydata =  this.tableRef.selectedRows[0]
      },
      pasteData(){
        // 黏贴数据
        for (var i=0;i<this.num;i++)
        {
          let data ={... this.copydata }
          data.id = ''
          data.rowNum = this.getRowNum()
          if(i !== 0){
            data.num = 0
          }
          console.log(data)
          this.bussProductStorageDetailTable.dataSource.push(data);
        }
        this.bussProductStorageDetailTable.dataSource.map(item =>{
          if(item.rowNum == this.copydata.rowNum){
            item.isDelete = 1
          }
        })
        // console.log(this.bussProductStorageDetailTable.dataSource)
      },
      warehouseOk({result,row}){
        this.bussProductStorageDetailTable.dataSource.forEach(item=>{
          if(item.materialId == row.materialId && item.rowNum == row.rowNum){
            item.erpLocationId = result.id
            item.erpLocationName = result.name
            item.erpLocationCode = result.code
            item.erpWarehouseName = result.warehouseName
            item.erpWarehouseCode = result.warehouseCode
          }
        })
        this.tableRef.resetScrollTop();
      },
      goodOk(rows){
        let _this = this;
        rows.forEach((item,index)=>{
          let obj = {
            materialId: item.id,
            materialName: item.name,
            materialCode: item.code,
            noticeDetailId: item.id,
            spec: item.noneSpec,
            rowNum: this.getRowNum(),
            storageType: this.model.storageType,
            materialTypeName: item.categoryCodeText.split(" ")[0],
            warehouseDate: moment(new Date()).format('YYYY-MM-DD'),
          }
          this.bussProductStorageDetailTable.dataSource.push(obj)
        })
        // this.formatterDatas();
      },
      addMaterial(){
        this.$nextTick(() => {
          this.$refs.good.add()
        })
      },
      bussinessOk({rows,callback}){
        const row = rows[0]
        this.$set(this.model,'businessNode',row.businessNode)
        this.$set(this.model,'materialTypeName',row.materialTypeName)
        this.$set(this.model,'businessType',row.businessType)
        this.$set(this.model,'materialTypeCode',row.materialTypeCode)
        callback(true)
      },
      onSearchBussiness(){
        this.$nextTick(()=>{
          this.$refs.bussinessType.add();
        })
      },
      addBefore(){
        this.bussProductStorageDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.bussProductStorageDetail.list, params, this.bussProductStorageDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          bussProductStorageDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      getRowNum(){
        let source = this.bussProductStorageDetailTable.dataSource
        if(source.length === 0){
          return '0001'
        }
        let { rowNum } = source[source.length-1]
        let nextRowNum = Number(rowNum) + 1;
        if(nextRowNum < 10){
          return '000'+ nextRowNum;
        }else if(nextRowNum < 100){
          return '00'+ nextRowNum;
        }else if(nextRowNum < 1000){
          return '0'+ nextRowNum;
        }else {
          return String(nextRowNum)
        }
      }

    }
  }
</script>

<style scoped>
</style>
<style>
.frozen-row {
  background-color: #eaf2fd; /* 更深的背景色 */
  font-weight: bold;
  color: #333; /* 可能需要调整文字颜色以提高对比度 */
}
.anticon-question-circle {
  display: none !important; /* 隐藏默认图标 */
}
</style>